<?php

class Init extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function index(){
        ECHO "<br/> 处理初始化数据工具";
        echo "<br/> aclprocess 导入tmpacl中的SRC字段重复问题处理";
        echo "<br/> ipnetworkcheck 根据nd_ip表的网段情况，检查nd_network表信息，并且补充完整本网段地址";
    }

    public function aclprocess(){
        set_time_limit(0);
        $query = $this->db->query("SELECT * FROM tmpacl");
        $num = $query->num_rows();
        $first = 0;
        $src = '';
        while ($first < $num){
            $query = $this->db->query("SELECT * FROM tmpacl LIMIT $first,1000");
            $result = $query->result_array();
            $updates = array();
            foreach ($result as $item){
                if ($item['SRC'] <> ''){
                    $src = $item['SRC'];
                } else {
                    $item['SRC'] = $src;
                    array_push($updates,$item);
                }
            }
            if (sizeof($updates) > 0){
                $this->db->update_batch("tmpacl",$updates,"ID");
            }
            $first = $first + 1000;
            echo "<br/> process ".($first-1000)." -> $first";
            ob_flush();
        }
        echo "<br/>UPDATE OK";
    }

    public function ipnetworkcheck(){
        set_time_limit(0);
        $networks = $this->db->query("select DISTINCT ID_NETWORK as ID_NETWORK from nd_ip")->result_array();
        foreach($networks as $nitem){
            $network = $this->db->get_where("nd_network",array("ID"=>$nitem["ID_NETWORK"]))->row_array();
            if ($network['STATUS'] === "IP已展开") continue;
            $network['STATUS'] = 'IP已展开';
            $this->db->update("nd_network",$network,array("ID"=>$network["ID"]));
            $inserts = array();
            $ip = $this->db->query("SELECT SUBSTRING_INDEX(IP,'.',-1) as IPN FROM nd_ip where ID_NETWORK=".$nitem['ID_NETWORK'])->result_array();
            $ip = array_column($ip,"IPN");
            for($i=1;$i<255;$i++){
                if(in_array($i,$ip)===false){
                    $insert = array();
                    $insert['ID_NETWORK'] = $nitem['ID_NETWORK'];
                    $iplist = explode(".",$network['NETWORK']);
                    $iplist[3] = $i;
                    $insert['IP'] = implode(".",$iplist);
                    $insert['TYPE'] = "其他地址";
                    $insert['STATUS'] = "未登录";
                    $insert['IS_DISABLED'] = 0;
                    $insert['createdatetime'] = Date("Y-m-d H:i:s");
                    $insert['createuser'] = "INPUT";
                    array_push($inserts,$insert);
                }
            }
            if (sizeof($inserts) > 0 )
                $this->db->insert_batch("nd_ip",$inserts);
            echo '<br/>'.$network['NETWORK'];
            flush();
        }
    }
}
